import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { trainingApi } from '@/api'
import { useWebSocket } from '@/composables'
import type {
    AICharacter,
    TrainingScenario,
    TrainingSession,
    Message,
    CreateSessionData,
    CharacterQueryParams,
    ScenarioQueryParams
} from '@/types'

export const useTrainingStore = defineStore('training', () => {
    // 状态
    const currentSession = ref<TrainingSession | null>(null)
    const messages = ref<Message[]>([])
    const aiCharacters = ref<AICharacter[]>([])
    const trainingScenarios = ref<TrainingScenario[]>([])
    const favoriteCharacters = ref<AICharacter[]>([])
    const isTraining = ref(false)
    const currentEmotionScore = ref(50)
    const loading = ref(false)

    // WebSocket相关
    const wsUrl = computed(() => {
        if (currentSession.value) {
            return `/ws/training/${currentSession.value.sessionUuid}`
        }
        return ''
    })

    const { connect, disconnect, emit, on, isConnected } = useWebSocket(wsUrl.value)

    // 计算属性
    const isSessionActive = computed(() => {
        return currentSession.value?.status === 'active'
    })

    const sessionDuration = computed(() => {
        if (!currentSession.value?.startedAt) return 0
        const start = new Date(currentSession.value.startedAt)
        const end = currentSession.value.completedAt
            ? new Date(currentSession.value.completedAt)
            : new Date()
        return Math.floor((end.getTime() - start.getTime()) / 1000)
    })

    // 方法
    async function fetchCharacters(params?: CharacterQueryParams) {
        try {
            loading.value = true
            const response = await trainingApi.getCharacters(params)

            if (params?.page === 1 || !params?.page) {
                aiCharacters.value = response.data
            } else {
                aiCharacters.value.push(...response.data)
            }

            return response
        } catch (error) {
            console.error('Failed to fetch characters:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    async function fetchScenarios(params?: ScenarioQueryParams) {
        try {
            loading.value = true
            const response = await trainingApi.getScenarios(params)

            if (params?.page === 1 || !params?.page) {
                trainingScenarios.value = response.data
            } else {
                trainingScenarios.value.push(...response.data)
            }

            return response
        } catch (error) {
            console.error('Failed to fetch scenarios:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    async function startTraining(data: CreateSessionData) {
        try {
            loading.value = true
            const session = await trainingApi.createSession(data)

            currentSession.value = session
            messages.value = []
            isTraining.value = true
            currentEmotionScore.value = 50

            // 建立WebSocket连接
            connect()
            setupWebSocketListeners()

            return session
        } catch (error) {
            console.error('Failed to start training:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    function setupWebSocketListeners() {
        // 监听AI消息
        on('ai-message', (data: { message: Message; emotionScore: number }) => {
            messages.value.push(data.message)
            currentEmotionScore.value = data.emotionScore
        })

        // 监听会话完成
        on('session-complete', (result: any) => {
            isTraining.value = false
            currentSession.value = { ...currentSession.value!, ...result }
        })

        // 监听连接错误
        on('error', (error: string) => {
            console.error('WebSocket error:', error)
        })
    }

    async function sendMessage(content: string) {
        if (!currentSession.value || !isConnected.value) return

        const userMessage: Message = {
            id: Date.now().toString(),
            sessionId: currentSession.value.id,
            sender: 'user',
            content,
            timestamp: new Date().toISOString(),
            type: 'text'
        }

        messages.value.push(userMessage)

        // 通过WebSocket发送消息
        emit('user-message', {
            sessionId: currentSession.value.sessionUuid,
            message: content
        })
    }

    async function endTraining() {
        if (!currentSession.value) return

        try {
            await trainingApi.completeSession(currentSession.value.sessionUuid)
            isTraining.value = false
            disconnect()
        } catch (error) {
            console.error('Failed to end training:', error)
            throw error
        }
    }

    async function toggleCharacterFavorite(characterId: number) {
        try {
            const character = aiCharacters.value.find(c => c.id === characterId)
            if (!character) return

            if (character.isFavorited) {
                await trainingApi.removeCharacterFavorite(characterId)
                character.isFavorited = false
                favoriteCharacters.value = favoriteCharacters.value.filter(c => c.id !== characterId)
            } else {
                await trainingApi.toggleCharacterFavorite(characterId)
                character.isFavorited = true
                favoriteCharacters.value.push(character)
            }
        } catch (error) {
            console.error('Failed to toggle character favorite:', error)
            throw error
        }
    }

    async function toggleScenarioFavorite(scenarioId: number) {
        try {
            const scenario = trainingScenarios.value.find(s => s.id === scenarioId)
            if (!scenario) return

            if (scenario.isFavorited) {
                await trainingApi.toggleScenarioFavorite(scenarioId)
                scenario.isFavorited = false
                // Remove from favorites list if it exists
                // favoriteScenarios.value = favoriteScenarios.value.filter(s => s.id !== scenarioId)
            } else {
                await trainingApi.toggleScenarioFavorite(scenarioId)
                scenario.isFavorited = true
                // Add to favorites list if it exists
                // favoriteScenarios.value.push(scenario)
            }
        } catch (error) {
            console.error('Failed to toggle scenario favorite:', error)
            throw error
        }
    }

    async function fetchFavoriteCharacters(userId: number) {
        try {
            const characters = await trainingApi.getCharacters({ userId, favorited: true })
            favoriteCharacters.value = characters.data
        } catch (error) {
            console.error('Failed to fetch favorite characters:', error)
        }
    }

    function clearSession() {
        currentSession.value = null
        messages.value = []
        isTraining.value = false
        currentEmotionScore.value = 50
        disconnect()
    }

    return {
        // 状态
        currentSession,
        messages,
        aiCharacters,
        trainingScenarios,
        favoriteCharacters,
        isTraining,
        currentEmotionScore,
        loading,
        isConnected,

        // 计算属性
        isSessionActive,
        sessionDuration,

        // 方法
        fetchCharacters,
        fetchScenarios,
        startTraining,
        sendMessage,
        endTraining,
        toggleCharacterFavorite,
        toggleScenarioFavorite,
        fetchFavoriteCharacters,
        clearSession,
    }
})